<?php

/**
 * This is the model class for table "{{media}}".
 *
 * The followings are the available columns in table '{{media}}':
 * @property integer $media_id
 * @property integer $media_cid
 * @property integer $media_uid
 * @property string $media_name
 * @property integer $media_pic_id
 * @property integer $media_recommend
 * @property integer $media_iscomment
 * @property integer $media_status
 * @property integer $media_created
 * @property integer $media_update
 * @property string $media_describe
 */
class Media extends CActiveRecord
{
    //是否允许评论
    const COMMENT_ALLOW = 1;
    const COMMENT_CANCEL = 0;

    //是否推荐
    const RECOMMEND_ALLOW = 1;
    const RECOMMEND_CANCEL = 0;

    //产品状态
    const STATUS_PUBLISHED = 1;
    const STATUS_LOCK = 0;
    const STATUS_DRAFT = 2;
    const STATUS_TRASH = 3;

    /**
     * Returns the static model of the specified AR class.
     * @return Media the static model class
     */
    public static function model($className = __class__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{media}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('media_cid, media_name, media_recommend, media_iscomment, media_status, media_describe',
                    'required'),
            array(
                'media_cid, media_uid, media_pic_id, media_recommend, media_iscomment, media_status, media_created, media_update',
                'numerical',
                'integerOnly' => true),
            array(
                'media_name',
                'length',
                'max' => 200),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array(
                'media_id, media_cid, media_uid, media_name, media_pic_id, media_recommend, media_iscomment, media_status, media_created, media_update, media_describe',
                'safe',
                'on' => 'search'),
            );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'file' => array(
                self::HAS_MANY,
                'File',
                'file_pid'),
            'folder' => array(
                self::HAS_ONE,
                'File',
                'file_id'),
            'owner' => array(
                self::BELONGS_TO,
                'User',
                'pro_uid'),
            'category' => array(
                self::BELONGS_TO,
                'Category',
                'media_cid'),
            'comment' => array(
                self::HAS_MANY,
                'Comment',
                'com_proid'),
            );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'media_id' => Yii::t('media', 'ID'),
            'media_cid' => Yii::t('media', 'Category'),
            'media_uid' => Yii::t('media', 'Owner'),
            'media_name' => Yii::t('media', 'Name'),
            'media_pic_id' => Yii::t('media', 'Folder'),
            'media_recommend' => Yii::t('media', 'Recommend'),
            'media_iscomment' => Yii::t('media', 'Comments'),
            'media_status' => Yii::t('media', 'Status'),
            'media_created' => Yii::t('media', 'Created'),
            'media_update' => Yii::t('media', 'Update'),
            'media_describe' => Yii::t('media', 'Describe'),
            );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('media_id', $this->media_id);
        $criteria->compare('media_cid', $this->media_cid);
        $criteria->compare('media_uid', $this->media_uid);
        $criteria->compare('media_name', $this->media_name, true);
        $criteria->compare('media_pic_id', $this->media_pic_id);
        $criteria->compare('media_recommend', $this->media_recommend);
        $criteria->compare('media_iscomment', $this->media_iscomment);
        $criteria->compare('media_status', $this->media_status);
        $criteria->compare('media_created', $this->media_created);
        $criteria->compare('media_update', $this->media_update);
        $criteria->compare('media_describe', $this->media_describe, true);

        return new CActiveDataProvider(get_class($this), array('criteria' => $criteria, ));
    }

    public function getRecommendState($state)
    {
        switch ($state) {
            case self::RECOMMEND_ALLOW:
                return Yii::t('common', 'ALLOW');
                break;
            case self::RECOMMEND_CANCEL:
                return Yii::t('common', 'CANCEL');
                break;
            default:
                return Yii::t('common', 'ALLOW');
        }
    }

    public function generateRecommendStateDropdownList()
    {
        return array(self::RECOMMEND_ALLOW => Yii::t('common', 'ALLOW'), self::
                RECOMMEND_CANCEL => Yii::t('common', 'CANCEL'));
    }

    public function getStatusState($state)
    {
        switch ($state) {
            case self::STATUS_DRAFT:
                return Yii::t('common', 'DRAFT');
                break;
            case self::STATUS_LOCK:
                return Yii::t('common', 'LOCK');
                break;
            case self::STATUS_PUBLISHED:
                return Yii::t('common', 'PUBLISHED');
                break;
            case self::STATUS_TRASH:
                return Yii::t('common', 'TRASH');
                break;
            default:
                return Yii::t('common', 'PUBLISHED');
                break;
        }
    }

    public function generateStatusStateDropdownList()
    {
        return array(
            self::STATUS_PUBLISHED => Yii::t('common', 'PUBLISHED'),
            self::STATUS_LOCK => Yii::t('common', 'LOCK'),
            self::STATUS_DRAFT => Yii::t('common', 'DRAFT'),
            self::STATUS_TRASH => Yii::t('common', 'TRASH'));
    }

    public function getCommentState($state)
    {
        switch ($state) {
            case self::COMMENT_ALLOW:
                return Yii::t('common', 'ALLOW');
                break;
            case self::COMMENT_CANCEL:
                return Yii::t('common', 'CANCEL');
                break;
        }
    }

    public function generateCommentStateDropdownList()
    {
        return array(self::COMMENT_ALLOW => self::getCommentState(self::COMMENT_ALLOW),
                self::COMMENT_CANCEL => self::getCommentState(self::COMMENT_CANCEL));
    }

    public function generateMediaList()
    {
        $arrlist = array();
        $i = 0;
        $model = self::model()->findAll();
        foreach ($model as $data) {
            $arrlist[$data->media_id] = $data->media_name;
            //			$i++;
        }
        return $arrlist;
    }

    public function getPictureList($id, $page = 1, $pageSize = 10)
    {
        $i = 0;
        
        $data = array();
        
        $criteria = new CDbCriteria(array(
            'condition' => 'file_status = :file_status AND file_pid = :file_pid',
            'order' => 'file_id DESC',
            'limit' => $page * $pageSize . ',' . $pageSize,
            'params' => array(':file_status' => File::FILE_STATUS_PUBLISHED, ':file_pid' =>$id)));

        $count = File::model()->count($criteria);
        $pages = new CPagination($count);

        // results per page
        $pages->pageSize = $pageSize;
        $pages->applyLimit($criteria);
        $model = File::model()->findAll($criteria);


        if ($model && $page < $pages->getPageCount()) {


            //   			for($i=0;$i<$num;$i++)
            //   			{
            //   				$pNum=rand(1,44);
            //   				$data[$i]["img"] = Yii::app()->theme->baseUrl."/assets/water/P".$pNum.".jpg";
            //   				$data[$i]["height"] = 0; //无高度值
            //   				$data[$i]["title"] = "时间：".date("Y-m-d H:i:s")."<br />".($i+1)."、WindsWaterFlow(第".$page."页)";
            //   			}


            foreach ($model as $item) {


                $data[$i]['folder'] = $item->file_pid;
                $data[$i]['img'] = File::model()->generateFilePath($item, false, true);
                $data[$i]['origionimg'] = File::model()->generateFilePath($item, false, false);
                //以height传ID值
                $data[$i]["height"] = 0; //无高度值
                $data[$i]["id"] = $item->file_id;
                $data[$i]['name'] = UtilString::strSlice($item->file_name, 0, 20);
                $data[$i]['created'] = date("Y-m-d H:i:s", $item->file_created);
                $data[$i]['pid'] = $item->file_pid;
                
                $i++;

            }

        }        
        return $data;
    }

    public function getMediaListInfo($page = 1, $pageSize = 10)
    {
        $data = array();
        $i = 0;

        $criteria = new CDbCriteria(array(
            'condition' => 'media_status = :media_status',
            'order' => 'media_id DESC',
            'limit' => $page * $pageSize . ',' . $pageSize,
            'params' => array(':media_status' => Media::STATUS_PUBLISHED, )));

        $count = Media::model()->count($criteria);
        $pages = new CPagination($count);

        // results per page
        $pages->pageSize = $pageSize;
        $pages->applyLimit($criteria);
        $model = Media::model()->findAll($criteria);

        if ($model !== null && $page < $pages->getPageCount()) {

            // 			for($i=0;$i<$num;$i++)
            // 			{
            // 				$pNum=rand(1,44);
            // 				$data[$i]["img"] = Yii::app()->theme->baseUrl."/assets/water/P".$pNum.".jpg";
            // 				$data[$i]["height"] = 0; //无高度值
            // 				$data[$i]["title"] = "时间：".date("Y-m-d H:i:s")."<br />".($i+1)."、WindsWaterFlow(第".$page."页)";
            // 			}

            foreach ($model as $item) {

                $fileModel = File::model()->findByPk($item->media_pic_id);
                $data[$i]['img'] = File::model()->generateFilePath($fileModel, false, true);
                $data[$i]["height"] = $item->media_cid; //无高度值
                $data[$i]['id'] = $item->media_id;
                $data[$i]['name'] = UtilString::strSlice($item->media_name, 0, 20);
//                $data[$i]['link'] = Yii::app()->createUrl('/work/view', array('id'=>$item->media_id));
                $data[$i]['created'] = date('Y-m-d H:i:s', $item->media_created);
                $data[$i]['describe'] = UtilString::strSlice($item->media_describe, 0, 50);

                $i++;
            }

        }

        return $data;
    }

    /**
     * This is invoked before the record is saved.
     * @return boolean whether the record should be saved.
     */
    protected function beforeSave()
    {
        if (parent::beforeSave()) {
            if ($this->isNewRecord) {
                $this->media_created = $this->media_update = time();
                $this->media_uid = Yii::app()->user->id;
            } else
                $this->media_update = time();
            return true;
        } else
            return false;
    }
}
